//
//  SearchViewController.m
//  EDPS
//
//  Created by 张维扬 on 15/11/23.
//  Copyright © 2015年 张维扬. All rights reserved.
//

#import "SearchViewController.h"
#import "ZWY_NetHandle.h"
#import "SearchModel.h"
#import "SearchCollectionViewCell.h"
#import "CityViewController.h"

@interface SearchViewController ()<UISearchResultsUpdating, UISearchBarDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UITableViewDataSource,UITableViewDelegate,UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,retain) UISearchController *searchController;
@property (nonatomic,retain) UICollectionView *collectionView;
@property (nonatomic,retain) UICollectionViewFlowLayout *layout;
@property (nonatomic,retain) NSMutableArray *CityArr;
@property (nonatomic,retain) UITableView *tableView;
@property (nonatomic,retain) NSMutableArray *tableDataArr;
@property (nonatomic,retain) NSMutableArray *BigArr;

@end

@implementation SearchViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.CityArr = [NSMutableArray array];
    self.tableDataArr = [NSMutableArray array];
    self.BigArr = [NSMutableArray array];
    [self creatCollection];
    [self creatSearch];
    [self creatData];
    [self creatTableView];
    self.tableView.hidden = YES;
}
- (void)creatSearch
{
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    self.searchController.searchResultsUpdater = self;
    self.searchController.dimsBackgroundDuringPresentation = NO;
    self.searchController.hidesNavigationBarDuringPresentation = NO;
    self.searchController.searchBar.frame = CGRectMake(30, self.view.frame.size.width / 75 * 4, self.view.frame.size.width - 60, self.view.frame.size.width / 75 * 8);
    self.searchController.searchBar.placeholder = @"搜索目的地";
    self.searchController.searchBar.searchBarStyle = UISearchBarStyleProminent;
    self.searchController.searchResultsUpdater = self;
    self.searchController.searchBar.delegate = self;
    self.navigationItem.titleView = self.searchController.searchBar;
}
- (void)creatCollection
{
    //collectionView
    self.layout = [[UICollectionViewFlowLayout alloc] init];
    self.layout.itemSize = CGSizeMake((self.view.frame.size.width / 3 * 2 - 25)/3 ,self.view.frame.size.width / 9 - 10 );
    self.layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    self.layout.minimumLineSpacing = 10;
    self.layout.minimumInteritemSpacing = 10;
    self.layout.sectionInset = UIEdgeInsetsMake(0,0,0,0);
    //头部大小
    self.layout.headerReferenceSize = CGSizeMake(self.view.frame.size.width, 60);
    //容器大小
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(20 ,0,ScreenWidth - 40, ScreenHeight) collectionViewLayout:self.layout];
    self.collectionView.backgroundColor = [UIColor clearColor];
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.view addSubview:self.collectionView];
    [self.collectionView registerClass:[SearchCollectionViewCell class] forCellWithReuseIdentifier:@"itm"];
    [self.collectionView registerClass:[SearchCollectionViewCell  class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
}
//头部信息
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    //从重用池中获取头部
    UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];
    headerView.backgroundColor = [UIColor clearColor];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width - 40, 30)];
    if (self.CityArr.count  != 0)
    {
        NSMutableDictionary *dic = [self.CityArr objectAtIndex:indexPath.section];
        label.text = [dic objectForKey:@"title"];
        label.textAlignment = 1;
    }
    label.textColor = RGBA(62, 172, 190, 1);
    [headerView addSubview:label];
    return headerView;
    
}
//分区数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return self.CityArr.count;
}

//行数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSMutableDictionary *dic = [self.CityArr objectAtIndex:section];
    NSMutableArray *datArr = [dic objectForKey:@"data"];
    return datArr.count;
}
//cell内容
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    SearchCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"itm" forIndexPath:indexPath];
    cell.layer.cornerRadius = 20 ;
    cell.layer.masksToBounds = YES;
    cell.layer.borderColor = RGBA(62, 172, 190, 1).CGColor;
    cell.layer.borderWidth = 0.8;
    cell.backgroundColor = [UIColor clearColor];
    NSMutableDictionary *dic = [self.CityArr objectAtIndex:indexPath.section];
    NSMutableArray *arr = [dic objectForKey:@"data"];
    NSMutableDictionary *odic = [arr objectAtIndex:indexPath.row];
    SearchModel *model = [[SearchModel alloc] init];
    [model setValuesForKeysWithDictionary:odic];
    cell.model = model;
    return cell;
}
//点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    CityViewController *cityUrl = [[CityViewController alloc] init];
    cityUrl.hidesBottomBarWhenPushed = YES;
    NSMutableDictionary *dic = [self.CityArr objectAtIndex:indexPath.section];
    NSMutableArray *arr = [dic objectForKey:@"data"];
    NSMutableDictionary *odic = [arr objectAtIndex:indexPath.row];
    NSString *url = [odic objectForKey:@"url"];
    NSString *appenUrl = [NSString stringWithFormat:@"http://web.breadtrip.com%@",url];
    cityUrl.url = appenUrl;
    [self.navigationController pushViewController:cityUrl animated:YES];
}
//serachBar 代理方法
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
   if ([self.searchController.searchBar.text isEqualToString:@""])
    {
        self.tableView.hidden = YES;
        self.collectionView.hidden = NO;
    }
    else
    {
        self.collectionView.hidden = YES;
        self.tableView.hidden = NO;
        NSPredicate *preicate = [NSPredicate predicateWithFormat:@"name CONTAINS[cd] %@",self.searchController.searchBar.text];
        if (self.tableDataArr != nil)
        {
            [self.tableDataArr removeAllObjects];
        }
        self.tableDataArr = [NSMutableArray arrayWithArray:[self.BigArr filteredArrayUsingPredicate:preicate]];
        [self.tableView reloadData];
    }
}
//UISearchController的移除
//在viewWillDisappear中要将UISearchController移除, 否则切换到下一个View中, 搜索框仍然会有短暂的存在.
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (self.searchController.active)
    {
        self.searchController.active = NO;
        [self.searchController.searchBar removeFromSuperview];
    }
}
- (void)creatTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,84, ScreenWidth, ScreenHeight - 64 - 20)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.tableDataArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"deq"];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"deq"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (self.searchController.active)
    {
        NSString *string = self.tableDataArr[indexPath.row][@"name"];
        NSMutableAttributedString *attrituteString = [[NSMutableAttributedString alloc] initWithString:string];
        NSRange range = [string rangeOfString:self.searchController.searchBar.text];
        [attrituteString setAttributes:@{NSForegroundColorAttributeName : RGBA(62, 172, 190, 1),   NSFontAttributeName : [UIFont systemFontOfSize:16]} range:range];
        cell.textLabel.attributedText = attrituteString;
        [cell.textLabel setFont:[UIFont systemFontOfSize:16]];
    }
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CityViewController *cityUrl = [[CityViewController alloc] init];
    NSMutableDictionary *dic = [self.tableDataArr objectAtIndex:indexPath.row];
    NSString *url = [dic objectForKey:@"url"];
    NSString *appenUrl = [NSString stringWithFormat:@"http://web.breadtrip.com%@",url];
    cityUrl.url = appenUrl;
    [self.navigationController pushViewController:cityUrl animated:YES];
}
//数据
- (void)creatData
{
    NSArray *arr = @[@"http://api.breadtrip.com/destination/index_places/3/",@"http://api.breadtrip.com/destination/index_places/6/",@"http://api.breadtrip.com/destination/index_places/8/"];
    for (NSInteger i = 0; i < 3; i ++)
    {
        [ZWY_NetHandle getURL:arr[i] Cookie:nil parameter:nil result:^(id result)
         {
             NSMutableDictionary *dic = result;
             [self.CityArr addObject:dic];
             for (NSDictionary *dictionary in dic[@"data"])
             {
                 [self.BigArr addObject:dictionary];
             }
             if (self.CityArr.count == 3)
             {
               [self.collectionView reloadData];
             }
             [self.tableView reloadData];
         }];
    }
}
@end